import { API } from '../config/http.config'
import { removeVaAPI } from '../utils/mock'
import { Orders, Categories, Products, Users, Role, Banners, Address, Favorites } from '../config/mock.config'
import { getOrInit, setToLS } from '../utils/mock'

export function setupStoreMock(mock) {
    mock.onGet(removeVaAPI(API.getHotProducts)).reply(config => {
        const products = getOrInit('Products', Products);
        const banners = getOrInit('Banners', Banners);

        // 优先展示banner对应的商品
        const bannerProductIds = banners.map(banner => {
            // 从banner.link (/product/p1) 中提取商品ID
            return banner.link.split('/').pop();
        });

        // 获取banner对应的商品
        let hotProductsData = [];
        bannerProductIds.forEach(productId => {
            const product = products.find(p => p.id.toString() === productId.toString() && p.status === 'on');
            if (product) {
                hotProductsData.push(product);
            }
        });

        // 如果banner商品不足5个，补充其他高销量商品
        if (hotProductsData.length < 5) {
            const remainingProducts = products
                .filter(product =>
                    product.status === 'on' &&
                    !bannerProductIds.includes(product.id.toString())
                )
                .sort((a, b) => b.sales - a.sales) // 按销量排序
                .slice(0, 5 - hotProductsData.length);
            hotProductsData = [...hotProductsData, ...remainingProducts];
        }

        return [200, hotProductsData.slice(0, 5)];
    });

    mock.onGet(removeVaAPI(API.getCategories)).reply(config => {
        const categories = getOrInit('Categories', Categories);
        return [200, categories];
    });

    mock.onGet(removeVaAPI(API.getBanners)).reply(config => {
        const banners = getOrInit('Banners', Banners);
        return [200, banners];
    });

    mock.onGet(removeVaAPI(API.getProducts)).reply(config => {
        console.log('Mock接收到请求:', config);
        const products = getOrInit('Products', Products);
        console.log('Mock商品总数:', products.length);
        
        let filteredProducts = products.filter(product =>
            product.status === 'on'
        );
        console.log('状态为on的商品数:', filteredProducts.length);
        
        // 处理搜索参数 - 修复参数获取方式
        let keyword = null;
        
        // 从URL参数中获取keyword
        if (config.params && config.params.keyword) {
            keyword = config.params.keyword;
        }
        
        // 从URL查询字符串中获取keyword
        if (!keyword && config.url && config.url.includes('?')) {
            const queryString = config.url.split('?')[1];
            const urlParams = new URLSearchParams(queryString);
            keyword = urlParams.get('keyword');
        }
        
        console.log('Mock搜索关键词:', keyword);
        
        if (keyword) {
            const keywordLower = keyword.toLowerCase();
            filteredProducts = filteredProducts.filter(product => {
                const nameMatch = product.name && product.name.toLowerCase().includes(keywordLower);
                const descMatch = product.description && product.description.toLowerCase().includes(keywordLower);
                return nameMatch || descMatch;
            });
            console.log('Mock过滤后商品数量:', filteredProducts.length);
            console.log('过滤后的商品:', filteredProducts);
        }
        
        // 确保返回的是有效数组
        const result = Array.isArray(filteredProducts) ? filteredProducts : [];
        console.log('Mock最终返回商品数量:', result.length);
        
        return [200, result];
    });

    mock.onPost(removeVaAPI(API.addOrder)).reply(config => {
        console.log(config.data);
        const order = JSON.parse(config.data);
        const orders = getOrInit('Orders', Orders);
        // 不重新分配ID，保持前端生成的ID
        if (!order.id) {
            order.id = Date.now().toString();
        }
        if (!order.createTime) {
            order.createTime = new Date().toISOString();
        }
        orders.push(order);
        setToLS('Orders', orders);
        return [200, { success: true, message: '订单添加成功', orderId: order.id }];
    });

    mock.onPost(removeVaAPI(API.cancelOrder)).reply(config => {
        let data = config.data;
        if (typeof data === 'string') {
            data = JSON.parse(data);
        }
        const orderId = data.id;
        const orders = getOrInit('Orders', Orders);
        const updatedOrders = orders.map(o => {
            if (o.id === orderId) {
                return { ...o, status: 'cancelled', cancelTime: new Date().toISOString() };
            }
            return o;
        });

        setToLS('Orders', updatedOrders);
        return [200, { success: true, message: '订单取消成功', orders: updatedOrders }];
    });

    mock.onPost(removeVaAPI(API.updateOrderById)).reply(config => {
        let data = config.data;
        if (typeof data === 'string') {
            data = JSON.parse(data);
        }
        const orderId = data.id;
        const orders = getOrInit('Orders', Orders);
        const updatedOrders = orders.map(o => {
            if (o.id === orderId) {
                return { ...o, ...data, updateTime: new Date().toISOString() };
            }
            return o;
        });

        setToLS('Orders', updatedOrders);
        return [200, { success: true, message: '订单更新成功', orders: updatedOrders }];
    });

    mock.onGet(removeVaAPI(API.getProductDetailById)).reply(config => {
        const productId = config.url.split('/').pop();
        const products = getOrInit('Products', Products);
        const product = products.find(p => p.id.toString() === productId.toString() && p.status === 'on');

        if (product) {
            return [200, product];
        } else {
            return [404, { message: 'Product not found' }];
        }
    });

    mock.onGet(removeVaAPI(API.getProductByCategory)).reply(config => {
        const categoryId = config.url.split('/').pop();
        const products = getOrInit('Products', Products);
        const filteredProducts = products.filter(p => {
            return p.categoryId.toString() === categoryId.toString() && p.status === 'on';
        });
        return [200, filteredProducts];
    });

    // 添加收藏相关的mock接口
    mock.onGet(removeVaAPI(API.getFavorites)).reply(config => {
        const favorites = getOrInit('Favorites', Favorites);
        const products = getOrInit('Products', Products);
        
        // 获取当前用户ID (在实际应用中应该从token或session中获取)
        const userId = 1; // 假设当前用户ID为1
        
        // 过滤出当前用户的收藏
        const userFavorites = favorites.filter(fav => fav.userId === userId);
        
        // 获取收藏的商品详情
        const favoriteProducts = userFavorites.map(fav => {
            const product = products.find(p => p.id === fav.productId);
            if (product) {
                return {
                    ...product,
                    addTime: fav.addTime
                };
            }
            return null;
        }).filter(Boolean);
        
        console.log('获取收藏列表:', favoriteProducts);
        return [200, favoriteProducts];
    });
    
    mock.onPost(removeVaAPI(API.addFavorite)).reply(config => {
        let data = config.data;
        if (typeof data === 'string') {
            data = JSON.parse(data);
        }
        
        const { productId } = data;
        const userId = 1; // 假设当前用户ID为1
        
        const favorites = getOrInit('Favorites', Favorites);
        
        // 检查是否已经收藏
        const existingFav = favorites.find(fav => 
            fav.userId === userId && fav.productId === productId
        );
        
        if (existingFav) {
            return [200, { success: false, message: '已经收藏过该商品' }];
        }
        
        // 添加收藏
        const newFavorite = {
            userId,
            productId,
            addTime: new Date().toISOString()
        };
        
        favorites.push(newFavorite);
        setToLS('Favorites', favorites);
        
        return [200, { success: true, message: '收藏成功' }];
    });
    
    mock.onPost(removeVaAPI(API.removeFavorite)).reply(config => {
        let data = config.data;
        if (typeof data === 'string') {
            data = JSON.parse(data);
        }
        
        const { productId } = data;
        const userId = 1; // 假设当前用户ID为1
        
        const favorites = getOrInit('Favorites', Favorites);
        
        // 过滤掉要删除的收藏
        const updatedFavorites = favorites.filter(fav => 
            !(fav.userId === userId && fav.productId === productId)
        );
        
        if (updatedFavorites.length === favorites.length) {
            return [200, { success: false, message: '未找到该收藏' }];
        }
        
        setToLS('Favorites', updatedFavorites);
        
        return [200, { success: true, message: '取消收藏成功' }];
    });
    
    mock.onGet(new RegExp(API.checkFavorite.replace(':id', '.*'))).reply(config => {
        const productId = config.url.split('/').pop();
        const userId = 1; // 假设当前用户ID为1
        
        const favorites = getOrInit('Favorites', Favorites);
        
        // 检查是否已收藏
        const isFavorite = favorites.some(fav => 
            fav.userId === userId && fav.productId === productId
        );
        
        return [200, { isFavorite }];
    });
}